﻿namespace CatClient.Util
{
    using CatClient.Configuration;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Runtime.InteropServices;
    using System.Text;

    internal static class HttpUtils
    {
        internal static string HttpGet(string url, Encoding encoding = null, int timeout = 0xbb8)
        {
            string str;
            RequestHandler handler = new RequestHandler();
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }
            try
            {
                using (Stream stream = handler.GetNetStream(url, timeout, "", null))
                {
                    str = new StreamReader(stream, encoding).ReadToEnd();
                }
            }
            catch (WebException exception)
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Warn($"HttpClientUtils get timeout error url:{url}", exception);
                str = string.Empty;
            }
            catch (Exception exception2)
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Error($"HttpClientUtils get error url:{url}", exception2);
                str = string.Empty;
            }
            return str;
        }
    }

    internal class RequestHandler
    {
        static RequestHandler()
        {
            ServicePointManager.DefaultConnectionLimit = 0x80;
            ServicePointManager.UseNagleAlgorithm = false;
            ServicePointManager.Expect100Continue = false;
        }

        public Stream GetFileStream(string url)
        {
            Stream stream = null;
            WebClient client1 = new WebClient();
            client1.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7");
            client1.Headers.Add("UserAgent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7");
            byte[] buffer = client1.DownloadData(url);
            if ((buffer != null) && (buffer.Length != 0))
            {
                stream = new MemoryStream(buffer);
            }
            return stream;
        }

        public Stream GetNetStream(string url, int timeout = 0xbb8, string contentType = "", Dictionary<string, string> addHeader = null)
        {
            HttpWebRequest request = null;
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "*/*";
            request.Referer = "";
            request.Headers["Accept-Language"] = "zh-cn";
            request.Headers["Accept-Encoding"] = "gzip,deflate";
            if (addHeader != null)
            {
                foreach (KeyValuePair<string, string> pair in addHeader)
                {
                    request.Headers.Add(pair.Key, pair.Value);
                }
            }
            request.ContentType = string.IsNullOrEmpty(contentType) ? "application/x-www-form-urlencoded" : contentType;
            request.Timeout = timeout;
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7";
            request.Proxy = null;
            return request.GetResponse().GetResponseStream();
        }

        public Stream Post(string url, string data, int timeout = 0xbb8, Dictionary<string, string> addHeader = null, string contentType = "")
        {
            HttpWebRequest request = null;
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "*/*";
            request.Referer = "";
            request.Headers["Accept-Language"] = "zh-cn";
            request.Headers["Accept-Encoding"] = "gzip,deflate";
            if (addHeader != null)
            {
                foreach (KeyValuePair<string, string> pair in addHeader)
                {
                    request.Headers.Add(pair.Key, pair.Value);
                }
            }
            request.Timeout = timeout;
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7";
            request.Proxy = null;
            request.Method = "POST";
            request.ContentType = string.IsNullOrEmpty(contentType) ? "application/x-www-form-urlencoded" : contentType;
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            return ((HttpWebResponse)request.GetResponse()).GetResponseStream();
        }
    }
}

